package com.erp.order.supply.controller;

import com.erp.hr.base.controller.BaseController;
import com.erp.hr.base.util.CommonUtils;
import com.erp.masterdata.vendor.dao.model.MdVendor;
import com.erp.masterdata.vendor.service.MdVendorService;
import com.erp.order.purchasing.model.PurchaseOrder;
import com.erp.order.purchasing.service.PurchaseOrderService;
import com.erp.order.purchasing.service.PurchasingRequisitionDetailService;
import com.erp.order.supply.model.SupplyMaterial;
import com.erp.order.supply.model.SupplyMaterialDetail;
import com.erp.order.supply.model.SupplyMaterialDetailR;
import com.erp.order.supply.model.SupplyMaterialR;
import com.erp.order.supply.service.SupplyMaterialDetailService;
import com.erp.order.supply.service.SupplyMaterialRService;
import com.erp.order.supply.service.SupplyMaterialService;
import org.redragon.framework.hibernate.model.Pages;
import org.redragon.framework.util.ShiroUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;
/*
 * 供应商供货
 */

@Controller
@RequestMapping("/web/supplyMaterial")
public class SupplyMaterialController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(SupplyMaterialController.class);

    @Autowired
    private SupplyMaterialService supplyMaterialService;

    @Autowired
    private SupplyMaterialRService supplyMaterialRService;

    @Autowired
    private SupplyMaterialDetailService supplyMaterialDetailService;

    @Autowired
    private PurchaseOrderService purchaseOrderService;

    @Autowired
    private MdVendorService mdVendorService;

    @Autowired
    private PurchasingRequisitionDetailService purchasingRequisitionDetailService;

    //获取供应商供货单
    @RequestMapping("getSupplyList")
    public String getSupplyList(Pages pages, PurchaseOrder purchaseOrder, Model model) {
        //当前登录人的登录名
        String username= ShiroUtil.getPrincipal();
        //分页查询数据
        if(pages.getPage()==0) {
            pages.setPage(1);
        }
        //分页查询数据
        List<PurchaseOrder> supplyList = this.purchaseOrderService.getDatasBySupplyid(username,purchaseOrder,pages);

        //页面属性设置
        model.addAttribute("supplyList", supplyList);
        model.addAttribute("order_status", supplyMaterialService.getDictByKey("purchase_order_status"));
        return "basic.jsp?content=mdVendor/supplyMaterialList";
    }

    //获取采购单id获取供货历史
    @RequestMapping("getHistoryList")
    public String getHistoryList(Pages pages, PurchaseOrder purchaseOrder, Model model) {
        //分页查询数据
        if(pages.getPage()==0) {
            pages.setPage(1);
        }
        //分页查询数据
        List<SupplyMaterialR>  supplyMaterialR=this.supplyMaterialRService.getDatasByOrderId(purchaseOrder.getId());
        //页面属性设置
        model.addAttribute("supplyRList", supplyMaterialR);
        model.addAttribute("order_status", supplyMaterialService.getDictByKey("purchase_order_status"));
        return "basic.jsp?content=mdVendor/suppliedList";
    }

    //根据供货单id获取供货明细
    @RequestMapping("getDetails")
    public String getDetailsById(Pages pages, SupplyMaterialR supplyMaterialR, Model model) {
        //分页查询数据
        if(pages.getPage()==0) {
            pages.setPage(1);
        }
        //分页查询数据
        List<SupplyMaterialDetail>  details=this.supplyMaterialDetailService.getDatasByRid(String.valueOf(supplyMaterialR.getId()));
        SupplyMaterialR info=this.supplyMaterialRService.getDataObjectById(String.valueOf(supplyMaterialR.getId()));
        //页面属性设置
        model.addAttribute("details", details);
        model.addAttribute("info", info);
        //物料单位
        model.addAttribute("unit", supplyMaterialService.getDictByKey("material_unit"));
        return "basic.jsp?content=mdVendor/suppliedDetail";
    }


    //获取供应商供货单详情信息
    @RequestMapping("getSupplyInfo")
    public String getSupplyInfo(PurchaseOrder purchaseOrder, Model model){
        Long id= purchaseOrder.getId();
        //采购单信息
        PurchaseOrder purchaseOrderInfo=this.purchaseOrderService.getDataObject(id);
        //采购物资集合
        List<SupplyMaterialDetailR>  details=this.purchasingRequisitionDetailService.getDetailsByOrderId(id);
        //供应商信息
        MdVendor mdVendor=this.mdVendorService.getDataObject(id.intValue());
        //根据采购单id获取供货次数
        List<SupplyMaterialR>  supplyMaterialR=this.supplyMaterialRService.getDatasByOrderId(id);

        //页面属性设置
        model.addAttribute("purchaseOrderInfo", purchaseOrderInfo);
        model.addAttribute("details", details);
        model.addAttribute("num", supplyMaterialR.size());
        model.addAttribute("mdVendor", mdVendor);
        //物料单位
        model.addAttribute("unit", supplyMaterialService.getDictByKey("material_unit"));
        //加载数据字典
        model.addAttribute("order_status", supplyMaterialService.getDictByKey("purchase_order_status"));

        return "basic.jsp?content=mdVendor/supplyMaterialsInfo";
    }

    @ResponseBody
    @RequestMapping("save")
    public Map<String,String> save(@RequestBody SupplyMaterial supplyMaterial) {
        Map map=new HashMap();
        int count=0;
        //如果是一次性供货，更新采购单状态
        if(supplyMaterial.getSupplyType().equals("0")){
            PurchaseOrder purchaseOrder=new PurchaseOrder();
            purchaseOrder.setId(Long.valueOf(supplyMaterial.getPurchaseOrderId()));
            purchaseOrder.setStatus("1");
            this.purchaseOrderService.insertOrUpdateDataObject(purchaseOrder);
        }

        SupplyMaterial supplyMaterial1=supplyMaterialService.getDataObject(supplyMaterial.getPurchaseOrderId());
        if(supplyMaterial1==null){
            //添加供货单（主）
            supplyMaterial.setCreateTime(new Date());
            supplyMaterial.setCreateUser(ShiroUtil.getPrincipal());
            this.supplyMaterialService.addCompleteData(supplyMaterial);
        }else{
            supplyMaterial.setId(supplyMaterial1.getId());
        }

        //添加供货单（副）
        SupplyMaterialR supplyMaterialR=supplyMaterial.getSupplyMaterialR();
        if(supplyMaterialR.getSendTime()==""){
            supplyMaterialR.setSendTime(null);
        }
        supplyMaterialR.setStatus("1");//未入库
        supplyMaterialR.setCreateTime(new Date());
        supplyMaterialR.setCreateUser(ShiroUtil.getPrincipal());
        supplyMaterialR.setSupplyMaterialId(String.valueOf(supplyMaterial.getId()));
        supplyMaterialR.setPurchaseOrderId(String.valueOf(supplyMaterial.getPurchaseOrderId()));
        setCode(supplyMaterialR);

        this.supplyMaterialRService.addCompleteData(supplyMaterial.getSupplyMaterialR());

        for (SupplyMaterialDetail detail:supplyMaterialR.getSupplyMaterialDetails()) {
            detail.setSupplyMaterialId(String.valueOf(supplyMaterial.getId()));
            detail.setSupplyMaterialRId(String.valueOf(supplyMaterialR.getId()));
            detail.setVendorId(String.valueOf(supplyMaterial.getVendorId()));
            detail.setCreateTime(new Date());
            detail.setCreateUser(ShiroUtil.getPrincipal());
            detail.setStatus("1");//未入库
            this.supplyMaterialDetailService.addCompleteData(detail);
            count++;
        }
        System.out.print(count);
        if(count==supplyMaterialR.getSupplyMaterialDetails().size()){
            map.put("result","success");
            map.put("message","供货成功！");
        }else{
            map.put("result","fail");
            map.put("message","报价失败！");
        }
        return map;
    }

    private void setCode(SupplyMaterialR supplyMaterialR) {
        StringBuilder sb = new StringBuilder();
        sb.append(CommonUtils.PREFIX_SUPPLY_LIST);
        Calendar calendar = Calendar.getInstance();
        sb.append(calendar.get(Calendar.YEAR));
        sb.append(calendar.get(Calendar.MONTH) + 1);
        sb.append(calendar.get(Calendar.DATE));
        sb.append(getCodeSuffix());
        supplyMaterialR.setCode(sb.toString());
    }
    /**
     * 获取询价编号后缀
     *
     */
    private String getCodeSuffix() {
        Integer num = supplyMaterialRService.getCreateCount() + 1;
        String suffix = num.toString();
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < CommonUtils.PURCHASING_REQUISITION_LENGRH - suffix.length(); i ++) {
            result.append("0");
        }
        result.append(suffix);
        return result.toString();
    }
}
